<?

class MAIL {
	function __construct( $type, $vars = false ){
		
		$this->type = $type;
		$this->done	= array();
		
		$this->modcon = new MOD_CONSTRUCT();
		if ($vars)
			$this->_addvars($vars);

		$this->update_db = false;
		
		if( !isset( $this->title )) $this->title = ACCOUNT;
		if( !isset($this->returnpath )) $this->returnpath = array( "news@" . engine_get( 'mail.ext' ) => engine_get( 'account' ) . " news"); 
	}
	
	function _addvars( $vars ){ foreach( $vars as $k=>$v ) if($k!=$this) $this->$k=$v; }
	
	function _parse_users( $get, $from, $where ){
		global $DB, $_init;
		
		$this->users = $DB->filter_key( "user_extend", $where, $get );
		//$this->users = $DB->parse($get,$from,$where,true);
	}
	
	function generate( $modid, $content ) {
		global $DB, $Engine;
		
		$this->_addvars( $this->modcon->request_json( $modid ));
		
		$replacevar = array(
			"%content%" => utf8_decode( $content )
		);
		
		$this->title = $Engine->text->get( $this->nameid );
		$this->html = $this->template_gen( $this->templateid, $replacevar );
	}
		
	function generate_newsletter( $letterid, $lang ) {
		global $DB, $Object, $Engine;
		
		// TEMP HOOK, SHOULD BE CHECKED!
		// ($Object will not always be present)
		if( !$Object && !$letterid ) return false;
		
		if( $letterid && ( !$Object || $Object->type != 'newsletter' ))
			$Object = new OBJECT( 'newsletter', $letterid );

		$this->_addvars( $this->modcon->request_json( engine_get( "style:mod.letter.vars" )));
		$Page = new PAGE( $this->location );
		
		$side = array();
		if( $Object->hasMedia() && $media = $Object->media->reference( "media.img" ))
			foreach ( $media as $el ) $side[] = "<img src='". engine_get( "url" ) ."/public.img?id=$el&sze={$this->imgsze}' />";

		$replacevar = array(
			"%date%"	=> date( "d.m Y", strtotime( $Object->get( "flog" ))),
			"%issue%"	=> $Object->id,
			"%year%"	=> $Object->get( "meta" )->year,
			"%url%"		=> $Page->url( "?letterid=". $Object->id ),
			"%style%"	=> PUBLIC_THEME . "/mailer",
			"%title%"	=> $this->title = utf8_decode( $Object->get( "name" )),
			"%side%"	=> implode( "\n", $side ),
			"%content%" => $Object->get( "content" )/*utf8_decode( $Object->get( "content" ))*/
		);		


		if( $this->mods )
			$replacevar = array_merge( $replacevar, $this->filter_mods());

		$this->html = $this->template_gen( $this->html_template, $replacevar );
		
		$replacevar[ '%content%' ] = strip_tags( $replacevar[ '%content%' ]);
		$this->plain = $this->template_gen( $this->plain_template, $replacevar );
	}
	
	function template_gen( $textid, $replace ) {
		global $Engine;

		$template = $Engine->text->get( $textid, "long" );
		
		return wordwrap(
			str_replace( array_keys( $replace ), array_values( $replace ), $template )
		);
	}
	
	function send( $conditional = 0, $log = false ) {
		global $DB;
		
		require_once ROOT . 'engine/ext/Swift/lib/swift_required.php';
		$count = 0;
		
		if( $this->users = $this->parseuser( $conditional )) {

		//	print_r( $this->users );

#			Create the message.
			$this->mail = Swift_Message::newInstance()
			
				->setSubject( $this->title )
				->setFrom( $this->returnpath )
				->setBody( $this->plain )
				->addPart( $this->html, "text/html" );


			while( $this->users && $parsed = $this->batch( 98 )) {
				
				if( $log ) $this->log( $parsed );
				$count += count( $parsed );
				
				sleep( 24 );
			}
		} 
		
		return $count;
	}
	
	function send_single( $conditional = 0, $log = false ) {
		global $DB;
		
		require_once ROOT . 'engine/ext/Swift/lib/swift_required.php';
		$count = 0;
		
		if( $this->users = $this->parseuser( $conditional )) {

#			Create the message.
			$this->mail = Swift_Message::newInstance()
			
				->setSubject( $this->title )
				->setFrom( $this->returnpath )
				->setBody( $this->plain )
				->addPart( $this->html, "text/html" );

			while( $this->users && $parsed = $this->batch( 98 )) {
				
				$count += count( $parsed );

			}
		} 
		
		return $count;
	}
	
	function batch( $amount ) {
		global $DB;
		
		set_time_limit( 80 );
		
		if( $amount > count( $this->users ))
			$amount = count( $this->users );

		
		foreach( $this->users as $mk => $ml ) if( ++$current <= $amount ) {

			if( $ml['meta'] ) $ml = array_merge( $ml, json_decode( $ml['meta'], true ));
			$adress = ( $ml['mail'] )? $ml['mail'] : $ml['user'];
				
			if( filter_var( $adress, FILTER_VALIDATE_EMAIL )) {
				
				$adresses[ $adress ] = ( $ml['fname'] )? $ml['fname']." ".$ml['lname'] : $ml['user'];
				$replace[ $adress ] = array('{email}'=>$adress, '{id}'=>$ml['ID']);
				$done[] = $ml['ID'];
					
			} else $DB->update( "user", (int) $ml[ 'ID' ], array( "active"=> 0 ));
			
			unset( $this->users[ $mk ]);
		}
		
		$this->mail->setTo( $adresses );
			
#		Create the Mailer.
		$mailer = Swift_Mailer::newInstance( Swift_SmtpTransport::newInstance( 'localhost' ));
		$mailer->registerPlugin( new Swift_Plugins_DecoratorPlugin( $replace ));

		$numSet = $mailer->batchSend( $this->mail );

		return ( $numSet )? $done : false;
	}
	
	function log( $parsed ) {
		global $DB, $Object;
		
		$DB->query( "insert into glue_social(parenttype, parentid, objid, objtype, active) select ". $DB->type( "newsletter" ) .", {$Object->id}, user.ID, user.type, 1 from user where user.ID in( ". implode( ",", $parsed ) ." )", 0 );
	}
	
	
	function parseuser( $id_or_where ) {
		global $DB;
		
		return $DB->filter_key( "user", $id_or_where, "user, ID, lang, meta" );
	}
	
	function filter_mods() {
		global $DB;
		
		include_once( ROOT . 'engine/ext/css_to_inline_styles/css_to_inline_styles.php' );
		
		$mods = array();
		foreach( $this->mods as $column => $ids )
			if( count( $ids )) foreach( $ids as $id ) {
			
				$Mod 	= $this->modcon->call(( int ) $id );
				$html	= $Mod->output();
				$css	= file_get_contents( engine_get( 'url' ) . '/style.mod?mods=' . $id );
				$css   .= file_get_contents( engine_get( 'url' ) . '/theme/' . engine_get( 'theme' ) . '/modules.css' );
				$output = new CSSToInlineStyles( $html, $css );
				$mods[ "%mods:$column%" ] .= $output->convert();
			}
				
		return $mods;
	}

}


?>